package com.xb.system.controller;

import com.xb.system.common.result.Result;
import com.xb.system.service.IOExcelService;
import com.xb.system.utils.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "3、执行判断流程")
@RestController
@RequestMapping("/admin/system/ioExcelService")
public class IOExcelController {

    @Autowired
    private IOExcelService ioExcelService;

    // 前端用户最大条数限制
    private static final int FRONTEND_MAX_RECORDS = 50000;
    
    // 后端文档对接最大条数限制
    private static final int BACKEND_MAX_RECORDS = 120000;

    @ApiOperation(value = "上传Excel文件并判定")
    @PostMapping("/input")
    public Result<String> inputMultipartFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
             Long userId = UserContext.getUserId();
            
            // 判断请求来源
            String referer = request.getHeader("Referer");
            String userAgent = request.getHeader("User-Agent");
            
            // 是否从Swagger/API文档访问
            boolean isFromApiDoc = (referer != null && (referer.contains("doc.html") || referer.contains("swagger"))) 
                                || (userAgent != null && userAgent.contains("Swagger"));
            
            // 根据来源设置不同的数据量限制
            int maxRecords = isFromApiDoc ? BACKEND_MAX_RECORDS : FRONTEND_MAX_RECORDS;
            
            // 处理文件并传入最大记录数限制
            String resultPath = ioExcelService.processExcelFile(file, userId, maxRecords);
            return Result.ok("判定完成，结果文件路径：" + resultPath);
        } catch (Exception e) {
            return Result.fail("判定失败：" + e.getMessage());
        }
    }
}
